/* eslint-disable no-unused-expressions */
/* eslint-disable no-empty */
/* eslint-disable no-console */
/* eslint-disable handle-callback-err */
/* eslint-disable camelcase */
/* eslint-disable no-undef */
/* eslint-disable space-before-function-paren */
/* eslint-disable indent */
/* eslint-disable global-require */
/* eslint-disable no-negated-condition */
/* eslint-disable no-unused-vars */
var baidu = require('baidu-aip-sdk');
var path = require('path');
var fs = require('fs');
var Recorder = require('js-audio-recorder');

var {
  shell,
  ipcRenderer
} = require('electron');
var SerialPort = require('serialport');
var formatSeconds = () => {
  return ''
}
var getProjectTitleFromFilename = fileInputFilename => {
  if (!fileInputFilename) return '';
  const matches = fileInputFilename.match(/^(.*)\.sb[23]?$/);
  if (!matches) return '';
  return matches[1].substring(0, 100); // truncate project title to max 100 chars
};

var readerx = fileToUpload => {
  let reader = new FileReader();
  reader.readAsArrayBuffer(fileToUpload);

  reader.onload = e => {
    vm.loadProject(reader.result)
      .then(_e => {
        try { // Can fail e.g. when GUI is loaded from static file (integration tests)
          history.replaceState({}, document.title, '.');
        } catch (err) { }
      })
      .catch(error => {
      });
  };
};


class Initclass {
  constructor() {
    this.AppID = '16400774';
    this.APIKey = 'CeOuAOvi7QZWPMXdjQWbPuP3';
    this.SecretKey = 'gPLS7F91SB7AGIlQSunqufX70oKRiASm';
    this.Recorder = Recorder;
    this.shell = shell;
    this.ipcRenderer = ipcRenderer;
    this.recorder = null;
    this.SerialPort = SerialPort;
    this.video = new Htevideo();
    this.timestamp = null
    this.getRecordAnalyseData = this.getRecordAnalyseData.bind(this)
    this.initstart = false
    this.duration = false
    this.num = 0
    this.color = "rgb(39,74,97)"
    this.gettime = '0:0'
    this.Recordloading = false
    this.time = {
      time: 0,
      start: 0
    }
  }

  /**
   * 初始化
   */

  start() {
    if (this.recorder) {
      this.recorder = null;
    }
    this.recorder = new Recorder({
      // sampleBits: 16,
      // sampleRate: 16000,
      // numChannels: 1,
    });
    this.recorder.start();

    if (this.recorder) {
      this.recorder.pause();
    }
    if (!this.initstart) {
      this.initstart = true
      this.video.enableVideo();
      this.timestamp = requestAnimationFrame(this.drawRecord)
      //document.querySelector(".drag").style.display = 'block'
    }

  }
  radar(i) {
    if (i) {
      //document.querySelector('.radar').style.display = 'none'

    } else {
      //document.querySelector('.radar').style.display = 'block'
    }
  }

  message(data) {

  }

  async setFaceinit(time, image, option = {}) {
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.face;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    const image_type = 'BASE64';
    option.face_field = 'age,beauty,expression,faceshape,gender,glasses,race,facetype';
    option.face_type = 'LIVE';
    option.max_face_num = '1';
    return client.detect(image, image_type, option);

  }

  async setgesture(time, image, option = {}) {
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.bodyanalysis;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.gesture(image, option);

  }

  async setbodyAttrtopwear(time, image, option = {}) {
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.bodyanalysis;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    option.type = 'lower_wear,upper_wear';
    return client.bodyAttr(image, option);
  }


  async setbodyAttrdownwear(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.bodyanalysis;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    option.type = 'lower_wear,upper_wear';
    return client.bodyAttr(image, option);
  }


  async setbodyNum(time, image, option = {}) {


    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.bodyanalysis;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);

    return client.bodyNum(image, option);

  }


  async setadvancedGeneral(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.advancedGeneral(image, option);

  }


  async setdishDetect(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    option.top_num = '1';
    return client.dishDetect(image, option);

  }


  async setcarDetect(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    option.top_num = '1';
    return client.carDetect(image, option);

  }


  async setlogoSearch(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    option.top_num = '1';
    return client.logoSearch(image, option);


  }


  async setanimalDetect(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.animalDetect(image, option);

  }

  async setplantDetect(time, image, option = {}) {


    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.plantDetect(image, option);


  }


  async setlandmark(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.imageClassify;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.landmark(image, option);

  }


  async setgeneralBasic(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.ocr;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.generalBasic(image, option);

  }
  async setwebimage(time, image, option = {}) {

    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.ocr;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.webImage(image, option);
  }


  async setidcard(time, image, option = {}) {
    const idCardSide = option.idCardSide || 'front';
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.ocr;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.idcard(image, idCardSide);
  }


  async sethandwriting(time, image, option = {}) {
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.ocr;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.handwriting(image, option);
  }

  async setnumbers(time, image, option = {}) {
    this.radar(false);
    for (let i = time / 1000; i > 0; i--) {
      this.num = i
      await this.delayed(1000);
    }
    this.radar(true);
    const AipFaceClient = baidu.ocr;
    const client = new AipFaceClient(this.AppID, this.APIKey, this.SecretKey);
    return client.numbers(image, option);
  }

  getRecordAnalyseData() {
    if (this.recorder) {
      const buffer = this.recorder.getRecordAnalyseData();
      return buffer
    }
    const buffer = []
    for (let i = 0; i < 1024; i++) {
      buffer.push(128);
    }
    return new Uint8Array(buffer)
  }

  /**
   * 绘制音频点
   */
  drawRecord(timestamp) {
    const oCanvas = document.getElementById("audiocanvas"); // 显示波形的canvas
    const ctx = oCanvas.getContext("2d");
    // 用requestAnimationFrame稳定60fps绘制
    requestAnimationFrame(electron.drawRecord)
    electron.gettime = formatSeconds(electron.video.video.currentTime)
    const canvas = {
      width: oCanvas.width,
      height: oCanvas.height
    };
    // 实时获取音频大小数据
    var dataArray = electron.getRecordAnalyseData(),
      bufferLength = dataArray.length;

    // 填充背景色
    ctx.fillStyle = electron.color;
    if (electron.time.time) {
      // 现在时间
      const d = new Date().getTime();
      const s = d - electron.time.start;
      const b = s / electron.time.time
      let c = b - 0.01
      let e = b + 0.01
      if (c < 0) {
        c = b
      }
      if (e > 1) {
        e = b
      }
      var my_gradient = ctx.createLinearGradient(0, 0, canvas.width, 0)
      my_gradient.addColorStop(0, "rgb(77,151,255)")
      my_gradient.addColorStop(c, "rgb(77,151,255)")
      my_gradient.addColorStop(b, "rgb(255,151,255)")
      my_gradient.addColorStop(e, "rgb(0,0,0)")
      my_gradient.addColorStop(1, "rgb(0,0,0)")
      ctx.fillStyle = my_gradient;
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    } else {
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }


    // 设定波形绘制颜色
    ctx.lineWidth = 2;
    ctx.strokeStyle = "rgb(226,231,234)";

    ctx.beginPath();

    var sliceWidth = (canvas.width * 1.0) / bufferLength, // 一个点占多少位置，共有bufferLength个点要绘制
      x = 0; // 绘制点的x轴位置

    for (var i = 0; i < bufferLength; i++) {
      var v = dataArray[i] / 128.0;
      var y = (v * canvas.height) / 2;

      if (i === 0) {
        // 第一个点
        ctx.moveTo(x, y);
      } else {
        // 剩余的点
        ctx.lineTo(x, y);
      }
      // 依次平移，绘制所有点
      x += sliceWidth;
    }

    ctx.lineTo(canvas.width, canvas.height / 2);
    ctx.stroke();
  }

  async htebaidu(devpid, time = 5000) {
    if (this.recorder) {
      this.recorder = null;
    }
    this.recorder = new Recorder({
      // sampleBits: 16,
      // sampleRate: 16000,
      // numChannels: 1,
    });
    this.recorder.start();
    this.color = "rgb(77,151,255)"
    this.time = {
      time: time,
      start: new Date().getTime()
    }
    await this.delayed(time);
    this.time = {
      time: 0,
      start: 0
    }
    this.Recordloading = true
    this.color = "rgb(39,74,97)"
    if (this.recorder) {
      this.recorder.pause();
    }
    console.log(this.recorder.duration);
    const buffer = this.recorder.getWAV();
    this.recorder.resume()
    const wav = new Blob([buffer]);
    const f = new FormData();
    f.append('wav', wav, 'a.wav');
    f.append('devpid', devpid);
    try {
      const data = await axios.post('https://public.hterobot.com/security/baidu/sound', f, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 15000,
      })
      this.Recordloading = false
      return new Promise(r => {
        r(data)
      })
    } catch (err) {
      this.Recordloading = false
      return new Promise((r, s) => {
        s(err)
      })
    }

  }


  delayed(time) {
    return new Promise((r) => {
      setTimeout(() => {
        r(true);
      }, time);
    });
  }

}

class Htevideo {
  constructor() {
    this.mediaStreamTrack = null;
    this.video = document.querySelector('video');
  }

  get mirror() {
    return this.mirror;
  }

  set mirror(state) {
    if (this.mirror !== state) {
      this.mirror = state;
    }
  }

  disableVideo() {
    this.mediaStreamTrack && this.mediaStreamTrack.stop();
  }

  enableVideo(state = 1) {
    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {};
    }
    const video = this.video;

    navigator.mediaDevices.getUserMedia({ video: true })
      .then(stream => {
        this.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
        video.srcObject = stream;
        video.onloadedmetadata = function (e) {
          video.play();
        };
      }).catch(function (err) { console.log(err.name + ": " + err.message); }); // 总是在最后检查错误
  }

  getimage() {
    const video = this.video;
    var canvas = document.getElementById("canvas");
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    canvas.getContext('2d')
      .drawImage(video, 0, 0, canvas.width, canvas.height);
    return canvas.toDataURL().split(',')[1]
  }

  setPreviewGhost(i) {

  }
}

// window.onload = async () => {


// };
